import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Form, Input, Button, Layout, Checkbox, Card, QRCode, message, Select } from 'antd';
import { useNavigate, useLocation, Navigate } from 'react-router-dom';
import { LockOutlined, UserOutlined, MobileOutlined } from '@ant-design/icons';
import { useAuth } from '@/components/auth';
import { useRootConfig } from '@/components/root-config';
import { useIntl } from '@/components/locale';
import sample from './img/login.mp4';
import './index.less';

const { Header, Content, Sider, Footer } = Layout;

/**
 * 登录页
 * 如果已登录重定向到from
 * @returns
 */
export default function LoginPage() {
    const intl = useIntl();
    const tabList = [
        {
            key: 'username_login',
            tab: intl.formatMessage({
                id: 'pages.login.accountLogin.tab',
                defaultMessage: '账户密码登录',
            }),
        },
        {
            key: 'email_login',
            tab: intl.formatMessage({
                id: 'pages.login.emailLogin.tab',
                defaultMessage: '邮箱登录',
            }),
        },
    ];
    const [messageApi, contextHolder] = message.useMessage();
    const navigate = useNavigate();
    const location = useLocation();
    const auth = useAuth();
    const { locale, setLocale } = useRootConfig();
    const from = location.state?.from?.pathname || '/portal/home';

    const [usernameForm] = Form.useForm();
    const [emailForm] = Form.useForm();
    const [loginType, setLoginType] = useState('username_login');
    const [loginByQr, setLoginByQr] = useState(false);
    const [time, setTime] = useState(60);
    const timerRef = useRef<NodeJS.Timeout | null>(null);

    // 页面卸载清空定时器
    useEffect(
        () => () => {
            if (timerRef.current) {
                clearInterval(timerRef.current);
                timerRef.current = null;
            }
        },
        [],
    );

    // 切换登录方式
    const onTabChange = useCallback(function onTabChange(key: string) {
        setLoginType(key);
    }, []);

    // form提交
    const onUsernameLoginFinish = useCallback(
        async (values: any) => {
            try {
                const { username, password, remember = false } = values;
                await auth.signin({ username, password, type: 'username' }).then(() => {
                    navigate(from, { replace: true });
                });
            } catch (error: any) {
                messageApi.open({
                    type: 'error',
                    content: error?.message,
                });
            }
        },
        [auth, messageApi, from, navigate],
    );
    const onEmailLoginFinish = useCallback(
        async (values: any) => {
            try {
                const { email, code, remember = false } = values;
                await auth
                    .signin({
                        email,
                        code,
                        type: 'email',
                    })
                    .then(() => {
                        navigate(from, { replace: true });
                    });
            } catch (error: any) {
                messageApi.open({
                    type: 'error',
                    content: error?.message,
                });
            }
        },
        [auth, from, messageApi, navigate],
    );

    // 获取短信验证码
    const getCode = useCallback(
        async function getCode() {
            try {
                if (time !== 60) return;
                await emailForm.validateFields(['email']);
                timerRef.current = setInterval(() => {
                    setTime((time) => {
                        const newTime = time - 1;
                        if (newTime <= 0) {
                            if (timerRef.current) {
                                clearInterval(timerRef.current);
                                timerRef.current = null;
                            }
                        }
                        return newTime <= 0 ? 60 : newTime;
                    });
                }, 1000);
            } catch (error) {
                // console.log(error);
            }
        },
        [emailForm, time],
    );

    // 已登录跳转到from页
    if (auth.user && localStorage.getItem('access_token')) {
        return <Navigate to={from} replace />;
    }

    return (
        <Layout className='w-full h-full'>
            {contextHolder}

            <Sider width='60%' theme='light'>
                <div className='video-wrap w-full h-full'>
                    <video className=' w-full h-full object-cover' muted autoPlay loop>
                        <source src={sample} type='video/mp4' />
                        <div className='login-page-sider w-full h-full bg-orange-300'> </div>
                    </video>
                </div>
            </Sider>
            <Layout>
                <Header className=' flex items-center justify-between leading-1'>
                    {intl.formatMessage({
                        id: 'pages.welcome.link',
                        defaultMessage: '欢迎使用',
                    })}
                    <Select
                        value={locale}
                        className=' w-32'
                        options={[
                            { value: 'zh-CN', label: '简体中文' },
                            { value: 'zh-TW', label: '繁體中文' },
                            { value: 'en-US', label: 'English' },
                        ]}
                        onChange={(value) => {
                            setLocale(value);
                        }}
                    />
                </Header>
                <Content className='p-10'>
                    {!loginByQr ? (
                        <Card
                            className=' relative mx-auto'
                            title='普通登录'
                            extra={
                                <div
                                    className='qr-code qr-code1'
                                    title='扫码登录'
                                    onClick={() => {
                                        setLoginByQr(true);
                                    }}
                                />
                            }
                            tabList={tabList}
                            activeTabKey={loginType}
                            onTabChange={onTabChange}
                        >
                            {loginType === 'username_login' && (
                                <Form
                                    form={usernameForm}
                                    name='username_login'
                                    initialValues={{ username: 'admin', password: '123456', remember: true }}
                                    onFinish={onUsernameLoginFinish}
                                    autoComplete='off'
                                >
                                    <Form.Item
                                        name='username'
                                        rules={[
                                            {
                                                required: true,
                                                message: intl.formatMessage({
                                                    id: 'pages.login.username.required',
                                                    defaultMessage: '用户名是必填项！',
                                                }),
                                            },
                                        ]}
                                    >
                                        <Input
                                            prefix={<UserOutlined />}
                                            placeholder={intl.formatMessage({
                                                id: 'pages.login.username.placeholder',
                                                defaultMessage: '用户名: admin or user',
                                            })}
                                        />
                                    </Form.Item>
                                    <Form.Item
                                        name='password'
                                        rules={[
                                            {
                                                required: true,
                                                message: intl.formatMessage({
                                                    id: 'pages.login.password.required',
                                                    defaultMessage: '密码是必填项！',
                                                }),
                                            },
                                        ]}
                                    >
                                        <Input
                                            type='password'
                                            placeholder={intl.formatMessage({
                                                id: 'pages.login.password.placeholder',
                                                defaultMessage: '密码: 123456',
                                            })}
                                            prefix={<LockOutlined />}
                                        />
                                    </Form.Item>
                                    <Form.Item>
                                        <Form.Item name='remember' valuePropName='checked' noStyle>
                                            <Checkbox>
                                                {intl.formatMessage({
                                                    id: 'pages.login.rememberMe',
                                                    defaultMessage: '自动登录',
                                                })}
                                            </Checkbox>
                                        </Form.Item>

                                        <Button className='login-form-forgot' type='link'>
                                            {intl.formatMessage({
                                                id: 'pages.login.forgotPassword',
                                                defaultMessage: '忘记密码 ?',
                                            })}
                                        </Button>
                                    </Form.Item>
                                    <Form.Item>
                                        <Button type='primary' htmlType='submit' className='login-form-button'>
                                            {intl.formatMessage({
                                                id: 'pages.login.submit',
                                                defaultMessage: '登录',
                                            })}
                                        </Button>
                                        <a href='register' className=' ml-4'>
                                            {intl.formatMessage({
                                                id: 'pages.login.registerAccount',
                                                defaultMessage: '注册账户',
                                            })}
                                        </a>
                                    </Form.Item>
                                </Form>
                            )}
                            {loginType === 'email_login' && (
                                <Form
                                    form={emailForm}
                                    name='email_login'
                                    initialValues={{ email: 'admin@qq.com', code: '666666', remember: true }}
                                    onFinish={onEmailLoginFinish}
                                    autoComplete='off'
                                >
                                    <Form.Item
                                        name='email'
                                        rules={[
                                            {
                                                required: true,
                                                message: intl.formatMessage({
                                                    id: 'pages.login.phoneNumber.required',
                                                    defaultMessage: '邮箱是必填项！',
                                                }),
                                            },
                                        ]}
                                    >
                                        <Input
                                            placeholder={intl.formatMessage({
                                                id: 'pages.login.phoneNumber.placeholder',
                                                defaultMessage: '请输入邮箱！',
                                            })}
                                            prefix={<MobileOutlined />}
                                        />
                                    </Form.Item>
                                    <Form.Item>
                                        <div className=' flex items-center gap-x-2'>
                                            <Form.Item
                                                name='code'
                                                rules={[
                                                    {
                                                        required: true,
                                                        message: intl.formatMessage({
                                                            id: 'pages.login.captcha.required',
                                                            defaultMessage: '验证码是必填项！',
                                                        }),
                                                    },
                                                ]}
                                                noStyle
                                            >
                                                <Input
                                                    className='flex-1'
                                                    placeholder={intl.formatMessage({
                                                        id: 'pages.login.captcha.placeholder',
                                                        defaultMessage: '请输入验证码！',
                                                    })}
                                                    prefix={<LockOutlined />}
                                                />
                                            </Form.Item>
                                            <Button disabled={time !== 60} onClick={getCode}>
                                                {time === 60 ? (
                                                    intl.formatMessage({
                                                        id: 'pages.login.phoneLogin.getVerificationCode',
                                                        defaultMessage: '获取验证码',
                                                    })
                                                ) : (
                                                    <>
                                                        {time}
                                                        {intl.formatMessage({
                                                            id: 'pages.getCaptchaSecondText',
                                                            defaultMessage: '秒后重新获取',
                                                        })}
                                                    </>
                                                )}
                                            </Button>
                                        </div>
                                    </Form.Item>
                                    <Form.Item>
                                        <Form.Item name='remember' valuePropName='checked' noStyle>
                                            <Checkbox>
                                                {intl.formatMessage({
                                                    id: 'pages.login.rememberMe',
                                                    defaultMessage: '自动登录',
                                                })}
                                            </Checkbox>
                                        </Form.Item>
                                        <Button className='login-form-forgot' type='link'>
                                            没有收到验证码?
                                        </Button>
                                    </Form.Item>
                                    <Form.Item>
                                        <Button type='primary' htmlType='submit' className='login-form-button'>
                                            {intl.formatMessage({
                                                id: 'pages.login.submit',
                                                defaultMessage: '登录',
                                            })}
                                        </Button>
                                        <a href='register' className=' ml-4'>
                                            {intl.formatMessage({
                                                id: 'pages.login.registerAccount',
                                                defaultMessage: '注册账户',
                                            })}
                                        </a>
                                    </Form.Item>
                                </Form>
                            )}
                        </Card>
                    ) : (
                        <Card
                            className=' relative mx-auto'
                            title='扫码登录'
                            extra={
                                <div
                                    className='qr-code qr-code2'
                                    title='普通登录'
                                    onClick={() => {
                                        setLoginByQr(false);
                                    }}
                                />
                            }
                        >
                            <div className=' flex flex-col items-center justify-center'>
                                <QRCode
                                    value='http://localhost:3000/'
                                    status='active'
                                    onRefresh={() => {
                                        //  console.log('refresh')
                                    }}
                                />
                                <div>打开“微信”，扫一扫登录</div>
                            </div>
                        </Card>
                    )}
                </Content>
                <Footer>yyds@1988</Footer>
            </Layout>
        </Layout>
    );
}
